import modelExtend from 'dva-model-extend'
import { query } from './services/financialSettlementApply'
import { lwjPageModel } from 'utils/model'
import { routerRedux } from 'dva/router';

export default modelExtend(lwjPageModel, {
  namespace: 'financialSettlementApply',
  state: {
    currentItem: {},
    selectRows: [],
    selectedRowKeys: [],
    pageOptions: {
      sort: 'createTime',
      order: 'DESC'
    },
    isExpand: false,
    queryParam: {},
    currentType:"SALES"
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/financialSettlementApply') {
          dispatch({ type: 'setCurrentTab', payload: "SALES" })
          dispatch({ type: 'query', payload: {} })
        }
      })
    }
  },
  effects: {
    * query({
      payload
    }, { select, call, put }) {
      yield put({
        type: 'asyncData',
        payload: {
          ...payload
        }
      });
      const pageOptions = yield select(({ financialSettlementApply }) => financialSettlementApply.pageOptions);
      const queryParam = yield select(({ financialSettlementApply }) => financialSettlementApply.queryParam);
      const currentType = yield select(({ financialSettlementApply }) => financialSettlementApply.currentType);
      const queryPayload = {
        ...pageOptions,
        queryParam: {
          ...queryParam,
          accountType:currentType
        }
      };
      const data = yield call(query, queryPayload);
      yield put({
        type: 'freshState',
        payload: {

        }
      })
      yield put({
        type: 'querySuccess',
        payload: {
          ...data
        }
      })
    },
    * showDetail({
      payload
    }, { select, call, put }) {
      yield put(routerRedux.push(`/financialSettlementApply/detail/${payload.recordId}`));
    },
    * doSettlement({
      payload
    }, { select, call, put }) {
      if (payload.doSettlementType === 'RECEIVABLE') {
        yield put(routerRedux.push('/financialSettlementApply/doSettlement4Receivable', { settlementApplies: payload.selectRows }));
      } else if (payload.doSettlementType === 'PAYABLE') {
        yield put(routerRedux.push('/financialSettlementApply/doSettlement4Payable', { settlementApplies: payload.selectRows }));
      }
    }
  },
  reducers: {
    onSelectChange(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    expandFilter(state, { payload }) {
      return {
        ...state,
        isExpand: true
      }
    },
    unExpandFilter(state, { payload }) {
      return {
        ...state,
        isExpand: false
      }
    },
    setCurrentTab(state, { payload }) {
      return {
        ...state,
        currentType: payload
      }
    },
    freshState(state, { payload }) {
      return {
        ...state,
        selectRows: [],
        selectedRowKeys: []
      }
    }
  }
})
